﻿/*
***********************************************************************
Software License Agreement

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
***********************************************************************

Author:
Hisham Kedjour (hkedjour@gmail.com)
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;

namespace JooJooTouchDriver
{
	partial class JooJooTouchDriverService : ServiceBase
	{
		private Thread _workerThread;

		public JooJooTouchDriverService()
		{
			InitializeComponent();
		}


		void WorkerThread()
		{
			var cb = new EGalaxTouch.EnumerateTouchscreenCallback(EnumerateTouchscreenCallback);

			EGalaxTouch.EnumerateTouchInstance(IntPtr.Zero, IntPtr.Zero, cb);
		}

		bool EnumerateTouchscreenCallback(IntPtr pContext, [MarshalAs(UnmanagedType.LPStr)]string szSymbolicName, uint nType)
		{
			IntPtr hDevice;

			hDevice = EGalaxTouch.CreateDevice(szSymbolicName);
			EGalaxTouch.EnableTouch(hDevice, false);
			EGalaxTouch.StartDeviceThread(hDevice);


			ulong branchInfo = 0;
			EGalaxTouch.GetBranchFormat(hDevice, ref branchInfo);
			branchInfo |= EGalaxTouch.BRANCH_ENABLED;
			EGalaxTouch.SetBranchFormat(hDevice, ref branchInfo);

			TouchHandlerForm frm = new TouchHandlerForm();
			EGalaxTouch.RegisterTPNotifyMessage(hDevice, frm.Handle, 0x0400 + 100);
			Application.Run(frm);


			EGalaxTouch.StopDeviceThread(hDevice);
			EGalaxTouch.EnableTouch(hDevice, true);
			EGalaxTouch.CloseDevice(hDevice);

			return true;
		}



		protected override void OnStart(string[] args)
		{
			if (_workerThread != null)
				return;



			try
			{
				string configFile = Path.Combine(GetType().Assembly.Location, @"..\Config.txt");

				using (var sw = new StreamReader(configFile))
				{
					var cnt = sw.ReadToEnd();

					if (cnt.Contains("x") || cnt.Contains("X"))
						AppSettings.InvertX = true;

					if (cnt.Contains("y") || cnt.Contains("Y"))
						AppSettings.InvertY = true;

					if (cnt.Contains("s") || cnt.Contains("S"))
						AppSettings.Swap = true;
				}

			}
			catch 
			{
			}

			_workerThread = new Thread(WorkerThread);
			_workerThread.SetApartmentState(ApartmentState.STA);
			_workerThread.Start();
		}
		protected override void OnStop()
		{
			if (_workerThread == null)
				return;

			Application.Exit();
			_workerThread.Join();
			_workerThread = null;
		}
	}
}
